<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-12-20 14:35:28
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-11-07 01:46:13
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Edit.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'
import { TableData } from '@/api/sp/die/types'
import { required } from '@/utils/formRules'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { TableLxq } from '@/components/Lxq'
import { zcAssetListApi } from '@/api/fa/earcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
import { zcPastureListApi } from '@/api/fa/pasture'
import { sysDictRelsApi } from '@/api/dict'
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'

const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))
const dictRelsData = ref() // 联动数据
const breedSubData: any = ref([]) // 品种的枚举
// const now = new Date()
const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])
const data = ref<any>({})
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  }
})

const getListAssetSelect = async () => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  await getList()
}
const getListAssetReste = async () => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  data.value.breed = ''
  data.value.breed_sub = ''
  data.value.asset_code = ''
  data.value.asset_code_2 = ''
  data.value.earcon_code = ''
  await getList()
}
const getListAsset = async (val) => {
  val.pasture_org_id = props.currentRow?.pasture_org_id
    ? props.currentRow?.pasture_org_id
    : data.value.pasture_org_id
  val.is_die = '0'
  val.breed = data.value.breed
  val.breed_sub = data.value.breed_sub
  val.asset_code = data.value.asset_code
  val.asset_code_2 = data.value.asset_code_2
  val.earcon_code = data.value.earcon_code
  return zcAssetListApi(val)
}

const { register, tableObject, methods, elTableRef } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getListAsset,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods
// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  await breedGetSub(value)
}
const clearBreed = async (value) => {
  data.value.breed = value
  data.value.breed_name = getDictLabel('breed', value)
  data.value.breed_sub = ''
  data.value.breed_sub_name = getDictLabel('breed_sub', '')
}
// 管理员用户列表
const myUserListChange = async (value) => {
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const props = {
    org_id: wsCache.get('userInfo').default_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi({ ...props })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
}
const DeptList = async (value) => {
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
}
const stateChangeAdminUser = async (value) => {
  data.value.admin_user_id = value
}
const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}
const UserList = async (value) => {
  data.value.pasture_dept_id = value
  await methodsForm.setValues(data.value)
  newUserData.value = []
  const props = {
    org_id: data.value.pasture_org_id,
    dept_id: data.value.pasture_dept_id
  }
  const res = await ucOrgDeptUserListApi({ ...props })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}

const onCustomer = async (value) => {
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  data.value.number = 0
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_user_id = ''
    await DeptList(value)
  }
  await methodsForm.setValues(data.value)
  await getList()
}

const schemaAdd = reactive<FormSchema[]>([
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '牧场用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'type',
    label: '死亡类型',
    component: 'Select',
    componentProps: {
      options: dict.die_type
    }
  },
  {
    field: 'number',
    label: '死亡数量',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '请选择资产'
    }
  },
  {
    component: 'DatePicker',
    field: 'die_time',
    label: '死亡时间',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'note',
    label: '死亡原因',
    component: 'Input',
    colProps: {
      span: 12
    }
  }
])
const schemaEdit = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    }
  },
  {
    field: 'admin_user_id',
    label: '管理用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeAdminUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'type',
    label: '死亡类型',
    component: 'Select',
    componentProps: {
      options: dict.die_type
    }
  },
  {
    field: 'number',
    label: '死亡数量',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '请选择资产'
    }
  },
  {
    component: 'DatePicker',
    field: 'die_time',
    label: '死亡时间',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'note',
    label: '死亡原因',
    component: 'Input',
    colProps: {
      span: 12
    }
  }
])
const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema: props.currentRow ? schemaEdit : schemaAdd
})
const rules = reactive({
  type: [required],
  die_time: [required],
  number: [required],
  // breed: [required],
  // breed_sub: [required],
  // note: [required],
  pasture_org_id: [required]
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methodsForm
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'id',
  //   label: '资产编号',
  //   search: {
  //     show: true
  //   }
  // },
  // {
  //   field: 'earcon_code',
  //   label: '耳标编号',
  //   width: 220,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    width: 200,
    label: '耳标编号',
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 220,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)

watch(
  () => data,
  (value) => {
    if (!value) return
    methodsForm.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => tableObject.tableList,
  (value) => {
    if (!value) return
    if (data.value.checkedAll) {
      setTimeout(() => {
        if (data.value.noSelectData.length > 0) {
          // 去重
          // console.log(tableObject.tableList, 'tableObject.tableList')
          // console.log('有没有未被选中的')
          let newArr = tableObject.tableList.filter(
            (x) => !data.value.noSelectData.some((item) => x.id == item.id)
          )
          newArr.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
          // console.log(newArr, 'newArr')
        } else {
          tableObject.tableList.forEach((row) => {
            elTableRef.value?.toggleRowSelection(row, true)
          })
        }
      }, 0)
    } else {
      if (data.value.selectData && data.value.selectData.length > 0) {
        data.value.selectData.forEach((row) => {
          elTableRef.value?.toggleRowSelection(row, true)
        })
      } else {
        data.value.selectData = []
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  return {
    ...formData
  }
}

defineExpose({
  methods: methods,
  data,
  getFormData,
  elFormRef
})

const init = async () => {
  await getDictRels()
  if (props.currentRow) {
    data.value.number = props.currentRow.number ? Number(props.currentRow.number) : 0
    data.value.pasture_org_id = props.currentRow.pasture_org_id
      ? props.currentRow.pasture_org_id
      : ''
    data.value.checkedAll =
      data.value.checkedAll !== undefined
        ? data.value.checkedAll
        : JSON.parse(props.currentRow.select_json).checkedAll
    data.value.breed = JSON.parse(props.currentRow.select_json).breed
    data.value.breed_sub = JSON.parse(props.currentRow.select_json).breed_sub
    data.value.asset_code = JSON.parse(props.currentRow.select_json).asset_code
    data.value.earcon_code = JSON.parse(props.currentRow.select_json).earcon_code
    if (data.value.breed) {
      await breedGetSub(data.value.breed)
    }
    if (data.value.checkedAll) {
      const aaa: any = []
      JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
        let obj: any = {}
        obj.id = element
        aaa.push(obj)
      })
      data.value.noSelectData = data.value.noSelectData != undefined ? data.value.noSelectData : aaa
    } else if (props.currentRow.select_json) {
      const aaa: any = []
      if (JSON.parse(props.currentRow.select_json).selected) {
        JSON.parse(props.currentRow.select_json).selected.forEach((element) => {
          let obj: any = {}
          obj.id = element
          aaa.push(obj)
        })
      }
      data.value.selectData = aaa
      // console.log(data.value.selectData, 'data.value.selectData', aaa)
    }
    if (props.currentRow.pasture_org_id) {
      await DeptList(props.currentRow.pasture_org_id)
    }
    if (props.currentRow.pasture_dept_id) {
      await UserList(props.currentRow.pasture_dept_id)
    }
    if (data.value.admin_dept_id) {
      const props = {
        org_id: wsCache.get('userInfo').default_org_id,
        dept_id: data.value.admin_dept_id
      }
      const res = await ucOrgDeptUserListApi({
        ...props
      })
        .catch(() => {})
        .finally(() => {})
      if (res) {
        myUserList.value = res.data
      }
    }
    //
    await getList()
  } else {
  }
  if (data.value.breed) {
    await breedGetSub(data.value.breed)
  }
}
init()

const getRowKey = (row) => {
  return row.id
}
</script>

<template>
  <div>
    <Form :rules="rules" @register="registerForm" />
  </div>
  <ContentWrap title="选择资产" v-if="data && data.pasture_org_id">
    <div>
      <el-form :inline="true" :model="data" class="demo-form-inline">
        <el-form-item label="注射编号">
          <el-input v-model="data.asset_code" />
        </el-form-item>
        <el-form-item label="项圈编号">
          <el-input v-model="data.asset_code_2" />
        </el-form-item>
        <el-form-item label="耳标编号">
          <el-input v-model="data.earcon_code" />
        </el-form-item>
        <el-form-item label="项圈编号">
          <el-input v-model="data.asset_code_2" />
        </el-form-item>
        <el-form-item label="畜别">
          <el-select
            v-model="data.breed"
            placeholder="请选择"
            clearable
            @clear="clearBreed"
            @change="breedChange"
          >
            <el-option
              v-for="item in dictRelsData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-select v-model="data.breed_sub" placeholder="请选择" clearable>
            <el-option
              v-for="item in breedSubData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getListAssetSelect">查询</el-button>
          <el-button type="" @click="getListAssetReste">重置</el-button>
        </el-form-item>
      </el-form>
      <TableLxq
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        v-model:checkedAll="data.checkedAll"
        v-model:noSelectData="data.noSelectData"
        v-model:selectData="data.selectData"
        v-model:total="tableObject.count"
        v-model:tableLen="data.number"
        :columns="allSchemas.tableColumns"
        :data="tableObject.tableList"
        :loading="tableObject.loading"
        :border="true"
        :pagination="{
          total: tableObject.count
        }"
        :row-key="getRowKey"
        :selection="true"
        highlight-current-row
        @register="register"
      />
    </div>
  </ContentWrap>
</template>
